package edu.cuit.zhuyimeng.framework.common.result;

import cn.hutool.core.lang.Assert;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;

import java.io.Serializable;
import java.util.Objects;

@Data
public class CommonResult<T> implements Serializable {

    /**
     * 状态码
     */
    private Integer code;

    /**
     * 错误提示，用户可阅读
     */
    private String msg;

    /**
     * 返回数据
     */
    private T data;

    /**
     * 将传入的 result 对象，转换成另外一个泛型结果的对象
     *
     * @param result 传入的 result 对象
     * @param <T>    返回的泛型
     * @return 新的 CommonResult 对象
     */
    public static <T> CommonResult<T> error(CommonResult<?> result) {
        return error(result.getCode(), result.getMsg());
    }

    public static <T> CommonResult<T> error(Integer code, String message) {
        Assert.isTrue(!HttpStatusCodeConstants.SUCCESS.getCode().equals(code), "code 应为错误码");
        CommonResult<T> result = new CommonResult<>();
        result.code = code;
        result.msg = message;
        return result;
    }

    public static <T> CommonResult<T> error(CodeWrapper errorCode) {
        return error(errorCode.getCode(), errorCode.getMsg());
    }
    public static <T> CommonResult<T> error(CodeWrapper errorCode,String msg) {
        return error(errorCode.getCode(), msg);
    }

    public static <T> CommonResult<T> error(String msg) {
        return error(HttpStatusCodeConstants.INTERNAL_SERVER_ERROR, msg);
    }

    public static <T> CommonResult<T> error() {
        CodeWrapper error = HttpStatusCodeConstants.INTERNAL_SERVER_ERROR;
        return error(error.getCode(), error.getMsg());
    }

    public static <T> CommonResult<T> success(T data) {
        CommonResult<T> result = new CommonResult<>();
        result.code = HttpStatusCodeConstants.SUCCESS.getCode();
        result.data = data;
        result.msg = HttpStatusCodeConstants.SUCCESS.getMsg();
        return result;
    }

    public static <T> CommonResult<T> success() {
        CommonResult<T> result = new CommonResult<>();
        result.code = HttpStatusCodeConstants.SUCCESS.getCode();
        result.msg = HttpStatusCodeConstants.SUCCESS.getMsg();
        return result;
    }

    public static <T> CommonResult<T> success(T data,String msg) {
        CommonResult<T> result = new CommonResult<>();
        result.code = HttpStatusCodeConstants.SUCCESS.getCode();
        result.msg = msg;
        result.data = data;
        return result;
    }

    public static boolean isSuccess(Integer code) {
        return Objects.equals(code, HttpStatusCodeConstants.SUCCESS.getCode());
    }

    @JsonIgnore
    public boolean isSuccess() {
        return isSuccess(code);
    }

    @JsonIgnore
    public boolean isError() {
        return !isSuccess();
    }


}
